---
title: "Application: Mass Mobilization in the Modern Era: Introducing the Opposition Movements and Groups (OMG) dataset, 1789-2019"
format:
  html:
    embed-resources: true
    code-fold: true
    code-summary: "Show the code"
    toc: true
    toc-location: left
editor: visual
---

# Preperations



```{r preperations, eval = TRUE}
rm(list=ls())

#This will downgrade your panelmatch. You need to do this if you have the updated (version3 or later). The script uses pre-version3 of PanelMatch. Updating changes the arguments.
# library(devtools)
# remove.package("PanelMatch")
# install_github("insongkim/PanelMatch", dependencies=TRUE) 
library(tidyverse);library(viridis);library(wesanderson);library(pals);library(readtext);library(stringi);library(ggpubr);library(haven);library(PanelMatch);library(xtable)


omg <- read_rds("Data/TheOMGDataset/R/omg.rds")
cy_omg <- read_rds("Data/TheOMGDataset/R/cy_omg.rds")
cy_omg <- as.data.frame(cy_omg)
far <- read_dta("Data/Fariss/latent_gdp_pc with V-Dem_id 1789-.dta")


#####     \\      --      Create a frame of onsets      --      //      #####

### Make filter for whenever we want to remove pro-regime campaigns.
omg$opposition_filter <- ifelse(omg$demand_regime_anti==1, 1,
                                ifelse(omg$demand_gov_anti==1, 1, 0))


onsets_frame <- omg %>% group_by(country_id, start_year) %>%
  summarise(onsets = n(),
            onset_violent            = max(ifelse(campaign_strategy_violent==1 & opposition_filter==0, 1, 0)),
            onset_nonviolent         = max(ifelse(campaign_strategy_violent==0 & opposition_filter==0, 1, 0)),
            
            onset_violent_flank            = max(ifelse(campaign_strategy_violent==1 & opposition_filter==0, 1,
                                                        ifelse(is.na(nv_violent_flank)==FALSE & nv_violent_flank==1 & opposition_filter==0, 1, 0) ) ),
            
            onset_nonviolent_flank            = max(ifelse(campaign_strategy_violent==0 & opposition_filter==0, 1,
                                                           ifelse(is.na(v_nonviolent_flank)==FALSE & v_nonviolent_flank==1 & opposition_filter==0, 1, 0) ) ),
            
            onset_violent_with_pro            = max(as.numeric(campaign_strategy_violent==1)),
            onset_nonviolent_with_pro         = max(as.numeric(campaign_strategy_violent==0)),
            
            onset_viol_auton         = max(ifelse(campaign_strategy_violent==1 & demand_main_autonomy     ==1, 1, 0)),
            onset_viol_secession     = max(ifelse(campaign_strategy_violent==1 & demand_main_secession    ==1, 1, 0)),
            onset_viol_gov           = max(ifelse(campaign_strategy_violent==1 & demand_main_remove_gov   ==1, 1, 0)),
            onset_viol_regime        = max(ifelse(campaign_strategy_violent==1 & demand_main_remove_regime==1, 1, 0)),
            onset_viol_institutional = max(ifelse(campaign_strategy_violent==1 & demand_main_institutional==1, 1, 0)),
            
            onset_nonviol_auton         = max(ifelse(campaign_strategy_violent==0 & demand_main_autonomy     ==1, 1, 0)),
            onset_nonviol_secession     = max(ifelse(campaign_strategy_violent==0 & demand_main_secession    ==1, 1, 0)),
            onset_nonviol_gov           = max(ifelse(campaign_strategy_violent==0 & demand_main_remove_gov   ==1, 1, 0)),
            onset_nonviol_regime        = max(ifelse(campaign_strategy_violent==0 & demand_main_remove_regime==1, 1, 0)),
            onset_nonviol_institutional = max(ifelse(campaign_strategy_violent==0 & demand_main_institutional==1, 1, 0)),
            
            onset_viol_workers       = max(ifelse(campaign_strategy_violent==1 & opposition_filter==0
                                                  & opposition_filter==0    & dominate_workers_general ==1, 1, 0)),
            onset_viol_students      = max(ifelse(campaign_strategy_violent==1 & opposition_filter==0
                                                  & opposition_filter==0    & dominate_students        ==1, 1, 0)),
            onset_viol_military      = max(ifelse(campaign_strategy_violent==1 & opposition_filter==0
                                                  & opposition_filter==0    & dominate_milemp          ==1, 1, 0)),
            onset_viol_peasants      = max(ifelse(campaign_strategy_violent==1 & opposition_filter==0
                                                  & opposition_filter==0    & dominate_peasant         ==1, 1, 0)),
            onset_viol_urbmid        = max(ifelse(campaign_strategy_violent==1 & opposition_filter==0
                                                  & opposition_filter==0    & dominate_urb_middle_class==1, 1, 0)),
            onset_viol_intellectuals = max(ifelse(campaign_strategy_violent==1 & opposition_filter==0
                                                  & opposition_filter==0    & dominate_intellectuals==1, 1, 0)),
            
            onset_nonviol_workers       = max(ifelse(campaign_strategy_violent==0 & opposition_filter==0
                                                     & opposition_filter==0 & dominate_workers_general ==1, 1, 0)),
            onset_nonviol_students      = max(ifelse(campaign_strategy_violent==0 & opposition_filter==0
                                                     & opposition_filter==0 & dominate_students        ==1, 1, 0)),
            onset_nonviol_military      = max(ifelse(campaign_strategy_violent==0 & opposition_filter==0
                                                     & opposition_filter==0 & dominate_milemp          ==1, 1, 0)),
            onset_nonviol_peasants      = max(ifelse(campaign_strategy_violent==0 & opposition_filter==0
                                                     & opposition_filter==0 & dominate_peasant         ==1, 1, 0)),
            onset_nonviol_urbmid        = max(ifelse(campaign_strategy_violent==0 & opposition_filter==0
                                                     & opposition_filter==0 & dominate_urb_middle_class==1, 1, 0)),
            onset_nonviol_intellectuals = max(ifelse(campaign_strategy_violent==0 & opposition_filter==0
                                                     & opposition_filter==0 & dominate_intellectuals   ==1, 1, 0)),
            
            
            
            onset_viol_ide_socialist_marxist       = max(ifelse(campaign_strategy_violent==1 & opposition_filter==0
                                                                & opposition_filter==0    & ide_socialist_marxist ==1, 1, 0)),
            onset_viol_ide_democracy_hr      = max(ifelse(campaign_strategy_violent==1 & opposition_filter==0
                                                          & opposition_filter==0    & ide_democracy_hr        ==1, 1, 0)),
            onset_viol_ide_nationalist      = max(ifelse(campaign_strategy_violent==1 & opposition_filter==0
                                                         & opposition_filter==0    & ide_nationalist          ==1, 1, 0)),
            onset_viol_ide_conservative      = max(ifelse(campaign_strategy_violent==1 & opposition_filter==0
                                                          & opposition_filter==0    & ide_conservative         ==1, 1, 0)),
            
            
            onset_nonviol_ide_socialist_marxist       = max(ifelse(campaign_strategy_violent==0 & opposition_filter==0
                                                                   & opposition_filter==0 & ide_socialist_marxist ==1, 1, 0)),
            onset_nonviol_ide_democracy_hr      = max(ifelse(campaign_strategy_violent==0 & opposition_filter==0
                                                             & opposition_filter==0 & ide_democracy_hr        ==1, 1, 0)),
            onset_nonviol_ide_nationalist      = max(ifelse(campaign_strategy_violent==0 & opposition_filter==0
                                                            & opposition_filter==0 & ide_nationalist          ==1, 1, 0)),
            onset_nonviol_ide_conservative      = max(ifelse(campaign_strategy_violent==0 & opposition_filter==0
                                                             & opposition_filter==0 & ide_conservative         ==1, 1, 0)),
            
            onset_viol_coord              = max(ifelse(campaign_strategy_violent==1 & opposition_filter==0
                                                       & opposition_filter==0 & coord_leaders        ==1, 1, 0)),
            onset_nonviol_coord           = max(ifelse(campaign_strategy_violent==0 & opposition_filter==0
                                                       & opposition_filter==0 & coord_leaders        ==1, 1, 0)),
            onset_viol_nocoord            = max(ifelse(campaign_strategy_violent==1 & opposition_filter==0
                                                       & opposition_filter==0 & coord_leaders        ==0, 1, 0)),
            onset_nonviol_nocoord         = max(ifelse(campaign_strategy_violent==0 & opposition_filter==0
                                                       & opposition_filter==0 & coord_leaders        ==0, 1, 0)))
onsets_frame$year <- onsets_frame$start_year
onsets_frame$start_year <- NULL


####      Get all valid country-years
tmp <- cy_omg[which(is.na(cy_omg$campaign_strategy_violent)==FALSE), c("country_id", "year")]
onsets_frame <- left_join(tmp, onsets_frame)
rm(tmp)
onsets_frame[is.na(onsets_frame)] <- 0 #Recode NA to 0 (no onsets)

#Join in
cy_omg <- left_join(cy_omg, onsets_frame)


#####     \\      --      Data prepping     --      //      #####
cy_omg <- left_join(cy_omg, far)
rm(far)

#####   Consistent timeseries
###     Need to make sure that the time series never skips a year:
cy_omg <- cy_omg[order(cy_omg$country_id, cy_omg$year), ]
cy_omg <- cy_omg %>% group_by(country_id) %>% mutate(last_year = lag(year))
cy_omg$timeinterval <- cy_omg$year - cy_omg$last_year

###     Create a frame of missing country-years (will have missing on all variables, but avoid any errors in lag later)
tmp <- cy_omg[which(cy_omg$timeinterval>1), c("country_id", "year", "timeinterval")]
tmp <- tmp[rep(seq_len(nrow(tmp)), tmp$timeinterval-1),]
tmp$one <- 1
tmp <- tmp %>% group_by(country_id) %>% mutate(duration = cumsum(one))
tmp$year <- tmp$year - tmp$duration

###     Clean columns
tmp$duration <- NULL
tmp$one <- NULL
tmp$timeinterval <- NULL
cy_omg$timeinterval <- NULL


###     Add missing country-years into data_cyear
cy_omg <- full_join(cy_omg, tmp)
cy_omg <- cy_omg[order(cy_omg$country_id, cy_omg$year), ]

#Change in polyarchy benchmark
cy_omg <- cy_omg %>% arrange(country_id, year) %>% group_by(country_id) %>% mutate("Polyarchy_10_years_ago" = lag(v2x_polyarchy, 10))
cy_omg$Polyarchy_10_year_change <- cy_omg$v2x_polyarchy - cy_omg$Polyarchy_10_years_ago

#Redefine
cy_omg$year <- as.numeric(cy_omg$year)

#All country-year combinations
fullframe <- expand_grid("country_id" = unique(cy_omg$country_id),
                         "year" = unique(cy_omg$year))
cy_omg <- left_join(cy_omg, fullframe)

#Why does this happen?
cy_omg <- cy_omg[!duplicated(cy_omg[, c("country_id", "year")]), ]
cy_omg <- as.data.frame(cy_omg)
cy_omg$country_id <- as.integer(cy_omg$country_id)
cy_omg$year <- as.integer(cy_omg$year)

#Change population-variable
cy_omg$ln_pop <- log(cy_omg$e_pop*10000)


# Add sum of successful coups for robustness
cy_omg <- cy_omg |> arrange(country_id, year) |> group_by(country_id) |> mutate("successful_coups" = cumsum( ifelse(is.na(e_coups), 0, e_coups) ) )



#Lag
cy_omg$ongoing_violent_with_flank <- ifelse(cy_omg$campaign_strategy_violent==1, 1,
                                            ifelse(cy_omg$nv_violent_flank==1, 1, 0))
cy_omg$ongoing_nonviolent_with_flank <- ifelse(cy_omg$campaign_strategy_nonviol==1, 1,
                                               ifelse(cy_omg$v_nonviolent_flank==1, 1, 0))


cy_omg <- cy_omg[order(cy_omg$country_id, cy_omg$year),]
cy_omg <- cy_omg %>% group_by(country_id) %>% mutate(campaign_strategy_violent_lag1 = lag(campaign_strategy_violent, 1),
                                                     campaign_strategy_nonviolent_lag1 = lag(campaign_strategy_nonviol, 1),
                                                     ongoing_violent_with_flank_lag1 = lag(ongoing_violent_with_flank),
                                                     ongoing_nonviolent_with_flank_lag1 = lag(ongoing_nonviolent_with_flank))


#Enforce data.frame
cy_omg <- as.data.frame(cy_omg)
cy_omg$country_id <- as.integer(cy_omg$country_id)
cy_omg$year <- as.integer(cy_omg$year)


#Function to extract panelmatch-result
panelmatch_resultframe <- function(panelestobject, y = NA, x = NA){
  tmp <- data.frame(summary(panelestobject)$summary, "QOI" = toupper(panelestobject$qoi), "treatment" = x, "outcome" = y, "matched_sets" = length(panelestobject$matched.sets))
  tmp$time <- 1:nrow(tmp)-1
  return(tmp)
}

get_pretrend_function <- function(p_mod, covs, strat, gol, dat){
  tmp <- data.frame(get_covariate_balance(p_mod$att, dat, covariates = covs, plot = FALSE))
  tmp$strategy <- strat
  tmp$goal <- gol
  tmp$time <- rownames(tmp)
  tmp_covs <- covs[covs %in% colnames(tmp)]
  tmp <- tmp %>% pivot_longer(cols = tmp_covs)
  
  return(tmp)
}




```

#Run PanelMatch() on full sample

```{r panelmatch_fullsample, eval = TRUE}
fullsample_modeldat <- cy_omg[, c("country_id", "year", "onset_nonviolent", "onset_violent", "campaign_strategy_violent_lag1", "v2x_polyarchy", "campaign_strategy_nonviolent_lag1", "latent_gdppc_mean_log", "ln_pop")]

#PanelMatch
mod_violent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = fullsample_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_violent", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_nonviolent, 1:10)) + I(lag(campaign_strategy_violent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)

#Stage 3
res_violent <- PanelEstimate(sets = mod_violent, data = fullsample_modeldat)

#PanelMatch
mod_nonviolent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = fullsample_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviolent", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #+ I(lag(campaign_strategy_nonviolent, 1:10)) + I(lag(campaign_strategy_violent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)

#Stage 3
res_nonviolent <- PanelEstimate(sets = mod_nonviolent, data = fullsample_modeldat)

```

## Pre-treatment trends

This extracts what is needed to plot pre-trends for the fullsample-results

```{r fullsample_pretrends, eval = TRUE}

pretreatment_violent <- data.frame(get_covariate_balance(mod_violent$att, fullsample_modeldat, covariates = c("v2x_polyarchy",
                                                                                                              "campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1", "latent_gdppc_mean_log", "ln_pop" ), plot = FALSE))
pretreatment_violent$strategy <- "Violent strategy"
pretreatment_violent$time <- rownames(pretreatment_violent)
pretreatment_violent <- pretreatment_violent %>% pivot_longer(cols = v2x_polyarchy:ln_pop)

pretreatment_nonviolent <- data.frame(get_covariate_balance(mod_nonviolent$att, fullsample_modeldat, covariates = c("v2x_polyarchy",
                                                                                                                    "campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1", "latent_gdppc_mean_log", "ln_pop" ), plot = FALSE))
pretreatment_nonviolent$strategy <- "Nonviolent strategy"
pretreatment_nonviolent$time <- rownames(pretreatment_nonviolent)
pretreatment_nonviolent <- pretreatment_nonviolent %>% pivot_longer(cols = v2x_polyarchy:ln_pop)


pretreatment_benchmark <- bind_rows(pretreatment_violent, pretreatment_nonviolent)
pretreatment_benchmark$strategy <-factor(pretreatment_benchmark$strategy, levels = c("Nonviolent strategy", "Violent strategy"))
pretreatment_benchmark$time <- gsub("t_", "T-", pretreatment_benchmark$time)
pretreatment_benchmark$time <- factor(pretreatment_benchmark$time, levels = paste0("T-", 10:1))
pretreatment_benchmark$time_num <- as.numeric(gsub("T", "", pretreatment_benchmark$time))

pretreatment_benchmark <- pretreatment_benchmark %>% mutate("Covariate" = case_when(
  name ==  "v2x_polyarchy" ~ "Polyarchy",
  name ==  "campaign_strategy_violent_lag1" ~ "Violent movements",
  name ==  "campaign_strategy_nonviolent_lag1" ~ "Nonviolent movements",
  name ==  "latent_gdppc_mean_log" ~ "Ln GDP per capita",
  name ==  "ln_pop" ~ "Ln population"))


fullsample_balance <- ggplot(pretreatment_benchmark, aes(x = time_num, y = value, color = Covariate)) +
  facet_wrap(~strategy) +
  geom_line() +
  geom_point() +
  xlab("Years before treatment") + ylab("Standardized Mean difference for experiencing onset") +
  scale_y_continuous(limits = c(-0.1, 0.1)) +
  scale_x_continuous(n.breaks = 10) +
  geom_hline(yintercept = 0) +
  theme_minimal() +
  theme(text = element_text(size = 18),
        axis.title.y = element_text(size = 16),
        strip.text = element_text(size = 16),
        strip.background = element_rect(fill = "grey80", color = "white"))
ggsave(filename = "Output/FigureC1.jpg", fullsample_balance, width = 12, heigh = 8)


```

## Plot fullsample-result

This plots the results for the PanelMatch of the full sample

```{r plot_fullsample, eval = TRUE}

#Result
fullsample_resframe <- data.frame(rbind(cbind(summary(res_violent)$summary,
                                              "Strategy"="Violent", "time" = paste0("t+", 0:10)),
                                        cbind(summary(res_nonviolent)$summary, "Strategy" = "Nonviolent", "time" = paste0("t+", 0:10))))
fullsample_resframe$estimate <- as.numeric(fullsample_resframe$estimate)
fullsample_resframe$X2.5. <- as.numeric(fullsample_resframe$X2.5.)
fullsample_resframe$X97.5. <- as.numeric(fullsample_resframe$X97.5.)
fullsample_resframe$time <- factor(fullsample_resframe$time, levels =  paste0("t+", 0:10))

fullsample_results <- ggplot(fullsample_resframe, aes(x = time, y = estimate, ymax = X97.5., ymin = X2.5., color = Strategy)) +
  geom_point(size = 4, position = position_dodge(width = 0.1)) +
  geom_errorbar(width = 0.1, linewidth = 2, position = position_dodge(width = 0.1)) +
  geom_hline(yintercept = 0) +
  theme_minimal() +
  xlab("Years since movement start") +
  ylab("Change in Polyarchy") +
  scale_color_manual(values = c("black", "grey")) +
  #labs(title = "ATT for campaigns of violent vs nonviolent strategy on Polyarchy over time") +
  theme(axis.text = element_text(size = 18),
        axis.title = element_text(size = 18),
        legend.text = element_text(size = 18),
        legend.title = element_text(size = 18),
        plot.title = element_text(size = 18))
ggsave(filename = "Output/Figure7.jpg", fullsample_results, width = 12, heigh = 8)

```

## Tabular Fullsample results

```{r tabular_fullsample, eval = TRUE}

#Result
fullsample_resframe <- data.frame(rbind(cbind(summary(res_violent)$summary,
                                              "Strategy"="Violent", "Time" = paste0("T+", 0:10)),
                                        cbind(summary(res_nonviolent)$summary, "Strategy" = "Nonviolent", "Time" = paste0("T+", 0:10))))
#fullsample_resframe$estimate  <- as.character(round(as.numeric(fullsample_resframe$estimate) , 4))
fullsample_resframe$estimate <- as.numeric(fullsample_resframe$estimate)
fullsample_resframe$std.error <- as.numeric(fullsample_resframe$std.error)

fullsample_resframe$estimate  <- ifelse(abs(fullsample_resframe$estimate) / abs(fullsample_resframe$std.error) >= 1.97,  paste0( as.character(round(as.numeric(fullsample_resframe$estimate) , 4)), "*"),
                                        as.character(round(as.numeric(fullsample_resframe$estimate) , 4)) )

fullsample_resframe$std.error <- paste0( "(", round(as.numeric(fullsample_resframe$std.error), 4), ")")
fullsample_resframe$X2.5.     <- as.numeric(fullsample_resframe$X2.5.)
fullsample_resframe$X97.5.    <- as.numeric(fullsample_resframe$X97.5.)
fullsample_resframe$Time <- factor(fullsample_resframe$Time, levels =  paste0("T+", 0:10))
fullsample_resframe <- fullsample_resframe[ , c("estimate", "std.error", "Time", "Strategy")]

viol_fullsample_resframe <- fullsample_resframe %>% subset(Strategy == "Violent") %>% pivot_longer(estimate:std.error, values_to = "Violent") %>% select(-Strategy)
nvio_fullsample_resframe <- fullsample_resframe %>% subset(Strategy == "Nonviolent") %>% pivot_longer(estimate:std.error, values_to = "Nonviolent") %>% select(-Strategy)

fullsample_resframe <- full_join(viol_fullsample_resframe, nvio_fullsample_resframe)
fullsample_resframe$name <- NULL

ndat <- tibble("Time" = c("N treated", "Sum of control units"),
               "Violent"     = as.character(c(length(res_violent$matched.sets)   , sum(sapply(res_violent$matched.sets   , function(x) length(x))) )),
               "Nonviolent" = as.character(c(length(res_nonviolent$matched.sets), sum(sapply(res_nonviolent$matched.sets, function(x) length(x))) )))
fullsample_resframe <- bind_rows(fullsample_resframe, ndat)
fullsample_resframe$Time[seq(2, nrow(fullsample_resframe)-2, 2)] <- ""

addtorow <- list()
addtorow$pos <- list(nrow(fullsample_resframe))
addtorow$command <- paste0(paste0('\\hline \\multicolumn{3}{l}{', "\\textit{* p \\textless 0.05. Standard errors in parentheses}", '}', collapse=''), '\\\\')



print(xtable(fullsample_resframe, caption = "ATT for violent vs. nonviolent protest movements on subsequent Polyarchy-
scores", label = "tab:Fullsample_results"), add.to.row = addtorow, include.rownames = FALSE, caption.placement = "top", size = "footnotesize",
hline.after = c(-1, 0, nrow(fullsample_resframe)-2),
table.placement = "!htbp", file = "Output/TableC1.tex")


```

## Plot fullsample-result for presentation

Attempt at presentation-friendly version

```{r plot_fullsample_for_presentation, eval = TRUE}

#Result
fullsample_resframe <- data.frame(rbind(cbind(summary(res_violent)$summary,
                                              "Strategy"="Violent", "time" = paste0("t+", 0:10)),
                                        cbind(summary(res_nonviolent)$summary, "Strategy" = "Nonviolent", "time" = paste0("t+", 0:10))))
fullsample_resframe$estimate <- as.numeric(fullsample_resframe$estimate)
fullsample_resframe$X2.5. <- as.numeric(fullsample_resframe$X2.5.)
fullsample_resframe$X97.5. <- as.numeric(fullsample_resframe$X97.5.)
fullsample_resframe$Time <- as.numeric(gsub("t+", "", fullsample_resframe$time, fixed = T))
fullsample_resframe$time <- factor(fullsample_resframe$time, levels =  paste0("t+", 0:10))


step1 <-fullsample_resframe %>% ungroup() %>% filter(Strategy!="Nonviolent") %>%  ggplot(aes(x = Time, y = estimate, ymax = X97.5., ymin = X2.5., fill = Strategy)) +
  #geom_point(size = 4, position = position_dodge(width = 0.1)) +
  #geom_errorbar(width = 0.1, linewidth = 2, position = position_dodge(width = 0.1)) +
  geom_line() +
  geom_ribbon(alpha = 0.7) +
  geom_hline(yintercept = 0) +
  theme_minimal() +
  xlab("Years since movement start") +
  ylab("Change in Polyarchy (Democracy)") +
  scale_color_manual(values = c("grey")) +
  scale_fill_manual(values  = c("grey")) +
  scale_x_continuous(breaks = seq(0, 10, 1)) +
  scale_y_continuous(breaks = seq(-0.025, 0.1, 0.025), limits = c(-0.025, 0.1)) +
  #labs(title = "ATT for campaigns of violent vs nonviolent strategy on Polyarchy over time") +
  theme(axis.text = element_text(size = 18),
        axis.title = element_text(size = 18),
        legend.text = element_text(size = 18),
        legend.title = element_text(size = 18),
        plot.title = element_text(size = 18),
        legend.position = "bottom")
ggsave(filename = "Output/Presentation_Fullsample_results_Step1.jpg", step1, width = 12, heigh = 8)


step2 <- fullsample_resframe %>% ungroup() %>%  ggplot(aes(x = Time, y = estimate, ymax = X97.5., ymin = X2.5., fill = Strategy)) +
  #geom_point(size = 4, position = position_dodge(width = 0.1)) +
  #geom_errorbar(width = 0.1, linewidth = 2, position = position_dodge(width = 0.1)) +
  geom_line() +
  geom_ribbon(alpha = 0.7) +
  geom_hline(yintercept = 0) +
  theme_minimal() +
  xlab("Years since movement start") +
  ylab("Change in Polyarchy (Democracy)") +
  scale_color_manual(values = c("black", "grey")) +
  scale_fill_manual(values = c("black", "grey")) +
  scale_x_continuous(breaks = seq(0, 10, 1)) +
  scale_y_continuous(breaks = seq(-0.025, 0.1, 0.025), limits = c(-0.025, 0.1)) +
  #labs(title = "ATT for campaigns of violent vs nonviolent strategy on Polyarchy over time") +
  theme(axis.text = element_text(size = 18),
        axis.title = element_text(size = 18),
        legend.text = element_text(size = 18),
        legend.title = element_text(size = 18),
        plot.title = element_text(size = 18),
        legend.position = "bottom")
ggsave(filename = "Output/Presentation_Fullsample_results_Step2.jpg", step2, width = 12, heigh = 8)

```

#Goal-separated


```{r panelmatch_goal, eval = TRUE}

goal_modeldat <- cy_omg[, c("country_id", "year", "campaign_strategy_violent_lag1", "v2x_polyarchy",
                            "campaign_strategy_nonviolent_lag1", "latent_gdppc_mean_log", "ln_pop",
                            #grep("treat\\_[a-z]*viol\\_", colnames(cy_omg), value =T),
                            grep("^onset_", colnames(cy_omg), value =T))]

#####     Autonomy

#PanelMatch
mod_auton_violent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = goal_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_viol_auton", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)

#Stage 3
res_auton_violent <- PanelEstimate(sets = mod_auton_violent, data = goal_modeldat)


#PanelMatch
mod_auton_nonviolent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = goal_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviol_auton", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)



#Stage 3
res_auton_nonviolent <- PanelEstimate(sets = mod_auton_nonviolent, data = goal_modeldat)


#####     Secession
#PanelMatch
mod_secession_violent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = goal_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_viol_secession", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)

#Stage 3
res_secession_violent <- PanelEstimate(sets = mod_secession_violent, data = goal_modeldat)


#PanelMatch
mod_secession_nonviolent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = goal_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviol_secession", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)


#Stage 3
res_secession_nonviolent <- PanelEstimate(sets = mod_secession_nonviolent, data = goal_modeldat)


#####     Removal of government
#PanelMatch
mod_gov_violent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = goal_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_viol_gov", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)


#Stage 3
res_gov_violent <- PanelEstimate(sets = mod_gov_violent, data = goal_modeldat)


#PanelMatch
mod_gov_nonviolent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = goal_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviol_gov", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)


#Stage 3
res_gov_nonviolent <- PanelEstimate(sets = mod_gov_nonviolent, data = goal_modeldat)


#####     Removal of regime
#PanelMatch
mod_regime_violent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = goal_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_viol_regime", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)


#Stage 3
res_regime_violent <- PanelEstimate(sets = mod_regime_violent, data = goal_modeldat)


#PanelMatch
mod_regime_nonviolent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = goal_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviol_regime", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  #exact.match.variables = NULL, #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent_lag1, 0:10)) + I(lag(campaign_strategy_nonviolent_lag1, 0:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)


#Stage 3
res_regime_nonviolent <- PanelEstimate(sets = mod_regime_nonviolent, data = goal_modeldat)


#####     Institutional changes
#PanelMatch
mod_institutional_violent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = goal_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_viol_institutional", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)


#Stage 3
res_institutional_violent <- PanelEstimate(sets = mod_institutional_violent, data = goal_modeldat)

#PanelMatch
mod_institutional_nonviolent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = goal_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviol_institutional", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)


#Stage 3
res_institutional_nonviolent <- PanelEstimate(sets = mod_institutional_nonviolent, data = goal_modeldat)

```

## Goal results

```{r, goal_results, eval = TRUE}

#####     Make results-frame
goal_results <- bind_rows(list(panelmatch_resultframe(res_auton_violent, y = "Polyarchy", x = "Violent autonomy"),
                               panelmatch_resultframe(res_auton_nonviolent, y = "Polyarchy", x = "Nonviolent autonomy"),
                               
                               panelmatch_resultframe(res_secession_violent, y = "Polyarchy", x = "Violent secession"),
                               panelmatch_resultframe(res_secession_nonviolent, y = "Polyarchy", x = "Nonviolent secession"),
                               
                               panelmatch_resultframe(res_gov_violent, y = "Polyarchy", x = "Violent remove gov"),
                               panelmatch_resultframe(res_gov_nonviolent, y = "Polyarchy", x = "Nonviolent remove gov"),
                               
                               panelmatch_resultframe(res_regime_violent, y = "Polyarchy", x = "Violent remove regime"),
                               panelmatch_resultframe(res_regime_nonviolent, y = "Polyarchy", x = "Nonviolent remove regime"),
                               
                               panelmatch_resultframe(res_institutional_violent, y = "Polyarchy", x = "Violent institutional"),
                               panelmatch_resultframe(res_institutional_nonviolent, y = "Polyarchy", x = "Nonviolent institutional")
))
goal_results$strategy <- gsub("(.*iolent) .*", "\\1", goal_results$treatment)
goal_results$goal <- str_to_title(gsub(".*iolent (.*)", "\\1", goal_results$treatment))
goal_results$goal <- factor(goal_results$goal, levels = c("Autonomy", "Secession", "Remove Gov", "Remove Regime", "Institutional"))
goal_results$time <- factor(goal_results$time, levels = c(0:10))

goal_result_plot <- ggplot(goal_results, aes(x = time, y = estimate, ymax = X97.5., ymin = X2.5.)) +
  facet_grid(goal ~ strategy) +
  geom_point(size = 4, position = position_dodge(width = 0.1)) +
  geom_errorbar(width = 0.1, linewidth = 2, position = position_dodge(width = 0.1)) +
  geom_hline(yintercept = 0) +
  theme_minimal() +
  xlab("Years since movement start") +
  ylab("Change in Polyarchy") +
  theme(axis.text = element_text(size = 18),
        axis.title = element_text(size = 18),
        legend.text = element_text(size = 18),
        legend.title = element_text(size = 18),
        plot.title = element_text(size = 18),
        strip.background = element_rect(fill = "grey80", color = "white"),
        strip.text = element_text(size = 18))
ggsave(filename = "Output/Figure9.jpg", goal_result_plot, width = 12, heigh = 12)


```

## Goal tabular

```{r tabular_goal, eval = TRUE}

#####     Make results-frame
goal_results <- bind_rows(list(panelmatch_resultframe(res_auton_violent, y = "Polyarchy", x = "Violent autonomy"),
                               panelmatch_resultframe(res_auton_nonviolent, y = "Polyarchy", x = "Nonviolent autonomy"),
                               
                               panelmatch_resultframe(res_secession_violent, y = "Polyarchy", x = "Violent secession"),
                               panelmatch_resultframe(res_secession_nonviolent, y = "Polyarchy", x = "Nonviolent secession"),
                               
                               panelmatch_resultframe(res_gov_violent, y = "Polyarchy", x = "Violent remove gov"),
                               panelmatch_resultframe(res_gov_nonviolent, y = "Polyarchy", x = "Nonviolent remove gov"),
                               
                               panelmatch_resultframe(res_regime_violent, y = "Polyarchy", x = "Violent remove regime"),
                               panelmatch_resultframe(res_regime_nonviolent, y = "Polyarchy", x = "Nonviolent remove regime"),
                               
                               panelmatch_resultframe(res_institutional_violent, y = "Polyarchy", x = "Violent institutional"),
                               panelmatch_resultframe(res_institutional_nonviolent, y = "Polyarchy", x = "Nonviolent institutional")
))
goal_results$strategy <- gsub("(.*iolent) .*", "\\1", goal_results$treatment)
goal_results$goal <- str_to_sentence(gsub(".*iolent (.*)", "\\1", goal_results$treatment))
goal_results$goal <- factor(goal_results$goal, levels = c("Autonomy", "Secession", "Remove gov", "Remove regime", "Institutional"))
goal_results$Time <- paste0("T+", goal_results$time)
goal_results$Time <- factor(goal_results$Time, levels =  paste0("T+", 0:10))
goal_results[, c("X2.5.", "X97.5.")] <- NULL
goal_results$estimate  <- ifelse(abs(goal_results$estimate) / abs(goal_results$std.error) >= 1.97,  paste0( as.character(round(as.numeric(goal_results$estimate) , 4)), "*"),
                                 as.character(round(as.numeric(goal_results$estimate) , 4)) )
goal_results$std.error <- paste0( "(", round(as.numeric(goal_results$std.error), 4), ")")
goal_results <- goal_results[ , c("estimate", "std.error", "Time", "treatment", "strategy", "goal")]


viol_goal_results <- goal_results %>% subset(strategy == "Violent") %>% pivot_longer(estimate:std.error, values_to = "Violent") %>% select(-treatment, -strategy)
viol_goal_results <- viol_goal_results %>% pivot_wider(names_from = goal, values_from = "Violent") %>% select(-name)

viol_ndat <- tibble("Time" = c("N treated", "Sum of control units"),
                    "Autonomy"      = as.character(c(length(res_auton_violent$matched.sets)        , sum(sapply(res_auton_violent$matched.sets   , function(x) length(x))) )),
                    "Secession"     = as.character(c(length(res_secession_violent$matched.sets)    , sum(sapply(res_secession_violent$matched.sets, function(x) length(x))) )), 
                    "Remove gov"    = as.character(c(length(res_gov_violent$matched.sets)          , sum(sapply(res_gov_violent$matched.sets, function(x) length(x))) )), 
                    "Remove regime" = as.character(c(length(res_regime_violent$matched.sets)       , sum(sapply(res_regime_violent$matched.sets, function(x) length(x))) )), 
                    "Institutional" = as.character(c(length(res_institutional_violent$matched.sets), sum(sapply(res_institutional_violent$matched.sets, function(x) length(x))) )) )
viol_goal_results <- bind_rows(viol_goal_results, viol_ndat)
viol_goal_results$Time[seq(2, nrow(viol_goal_results)-2, 2)] <- ""


nvio_goal_results <- goal_results %>% subset(strategy == "Nonviolent") %>% pivot_longer(estimate:std.error, values_to = "Nonviolent") %>% select(-treatment, -strategy)
nvio_goal_results <- nvio_goal_results %>% pivot_wider(names_from = goal, values_from = "Nonviolent") %>% select(-name)

nvio_ndat <- tibble("Time" = c("N treated", "Sum of control units"),
                    "Autonomy"      = as.character(c(length(res_auton_nonviolent$matched.sets)         , sum(sapply(res_auton_nonviolent$matched.sets, function(x) length(x))) )),
                    "Secession"     = as.character(c(length(res_secession_nonviolent$matched.sets)     , sum(sapply(res_secession_nonviolent$matched.sets, function(x) length(x))) )), 
                    "Remove gov"    = as.character(c(length(res_gov_nonviolent$matched.sets)           , sum(sapply(res_gov_nonviolent$matched.sets, function(x) length(x))) )), 
                    "Remove regime" = as.character(c(length(res_regime_nonviolent$matched.sets)        , sum(sapply(res_regime_nonviolent$matched.sets, function(x) length(x))) )), 
                    "Institutional" = as.character(c(length(res_institutional_nonviolent$matched.sets) , sum(sapply(res_institutional_nonviolent$matched.sets, function(x) length(x))) )) )
nvio_goal_results <- bind_rows(nvio_goal_results, nvio_ndat)
nvio_goal_results$Time[seq(2, nrow(nvio_goal_results)-2, 2)] <- ""

addtorow <- list()
addtorow$pos <- list(nrow(viol_goal_results))
addtorow$command <- paste0(paste0('\\hline \\multicolumn{5}{l}{', "\\textit{* p \\textless 0.05. Standard errors in parentheses}", '}', collapse=''), '\\\\')

#
print(xtable(viol_goal_results, caption = "ATT for violent protest movements on subsequent Polyarchy-
scores across different goals", label = "tab:goal_results_violent"), add.to.row = addtorow, include.rownames = FALSE, caption.placement = "top", size = "scriptsize",
hline.after = c(-1, 0, nrow(viol_goal_results)-2),
table.placement = "!htbp", file = "Output/TableC4.tex")

print(xtable(nvio_goal_results, caption = "ATT for nonviolent protest movements on subsequent Polyarchy-
scores across different goals", label = "tab:goal_results_nonviolent"), add.to.row = addtorow, include.rownames = FALSE, caption.placement = "top", size = "scriptsize",
hline.after = c(-1, 0, nrow(nvio_goal_results)-2),
table.placement = "!htbp", file = "Output/TableC5.tex")


```

# Participating social group


```{r panelmatch_socgroup, eval = TRUE}
socgroup_modeldat <- cy_omg[, c("country_id", "year", "campaign_strategy_violent_lag1", "v2x_polyarchy", "campaign_strategy_nonviolent_lag1", "latent_gdppc_mean_log", "ln_pop",
                                grep("^onset_", colnames(cy_omg), value =T))]

#####     Workers
#PanelMatch
mod_workers_violent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = socgroup_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_viol_workers", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
)

#Stage 3
res_workers_violent <- PanelEstimate(sets = mod_workers_violent, data = socgroup_modeldat)


#PanelMatch
mod_workers_nonviolent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = socgroup_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviol_workers", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)



#Stage 3
res_workers_nonviolent <- PanelEstimate(sets = mod_workers_nonviolent, data = socgroup_modeldat)



#####    Students
#PanelMatch
mod_students_violent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = socgroup_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_viol_students", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)

#Stage 3
res_students_violent <- PanelEstimate(sets = mod_students_violent, data = socgroup_modeldat)


#PanelMatch
mod_students_nonviolent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = socgroup_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviol_students", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)

#Stage 3
res_students_nonviolent <- PanelEstimate(sets = mod_students_nonviolent, data = socgroup_modeldat)


#####     Military
#PanelMatch
mod_military_violent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = socgroup_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_viol_military", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)

#Stage 3
res_military_violent <- PanelEstimate(sets = mod_military_violent, data = socgroup_modeldat)


#PanelMatch
mod_military_nonviolent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = socgroup_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviol_military", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)

#Stage 3
res_military_nonviolent <- PanelEstimate(sets = mod_military_nonviolent, data = socgroup_modeldat)


#####     Peasants
#PanelMatch
mod_peasants_violent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = socgroup_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_viol_peasants", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
)

#Stage 3
res_peasants_violent <- PanelEstimate(sets = mod_peasants_violent, data = socgroup_modeldat)


#PanelMatch
mod_peasants_nonviolent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = socgroup_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviol_peasants", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
)

#Stage 3
res_peasants_nonviolent <- PanelEstimate(sets = mod_peasants_nonviolent, data = socgroup_modeldat)


#####     Urban middle class
#PanelMatch
mod_urbmid_violent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = socgroup_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_viol_urbmid", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
)

#Stage 3
res_urbmid_violent <- PanelEstimate(sets = mod_urbmid_violent, data = socgroup_modeldat)


#PanelMatch
mod_urbmid_nonviolent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = socgroup_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviol_urbmid", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
)

#Stage 3
res_urbmid_nonviolent <- PanelEstimate(sets = mod_urbmid_nonviolent, data = socgroup_modeldat)

#####     Intellectuals

#PanelMatch
mod_intellectuals_violent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = socgroup_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_viol_intellectuals", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
)

#Stage 3
res_intellectuals_violent <- PanelEstimate(sets = mod_intellectuals_violent, data = socgroup_modeldat)


#PanelMatch
mod_intellectuals_nonviolent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = socgroup_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviol_intellectuals", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
)

#Stage 3
res_intellectuals_nonviolent <- PanelEstimate(sets = mod_intellectuals_nonviolent, data = socgroup_modeldat)


```

## Social group results

```{r socgroup_results, eval = TRUE}

#####     Make results-frame
socgroup_result <- bind_rows(list(panelmatch_resultframe(res_workers_violent, y = "Polyarchy", x = "Violent Workers"),
                                  panelmatch_resultframe(res_workers_nonviolent, y = "Polyarchy", x = "Nonviolent Workers"),
                                  
                                  panelmatch_resultframe(res_students_violent, y = "Polyarchy", x = "Violent Students"),
                                  panelmatch_resultframe(res_students_nonviolent, y = "Polyarchy", x = "Nonviolent Students"),
                                  
                                  panelmatch_resultframe(res_military_violent, y = "Polyarchy", x = "Violent Military"),
                                  panelmatch_resultframe(res_military_nonviolent, y = "Polyarchy", x = "Nonviolent Military"),
                                  
                                  panelmatch_resultframe(res_peasants_violent, y = "Polyarchy", x = "Violent Peasants"),
                                  panelmatch_resultframe(res_peasants_nonviolent, y = "Polyarchy", x = "Nonviolent Peasants"),
                                  
                                  panelmatch_resultframe(res_urbmid_violent, y = "Polyarchy", x = "Violent Urban mid. class"),
                                  panelmatch_resultframe(res_urbmid_nonviolent, y = "Polyarchy", x = "Nonviolent Urban mid. class"),
                                  
                                  panelmatch_resultframe(res_intellectuals_violent, y = "Polyarchy", x = "Violent Intellectuals"),
                                  panelmatch_resultframe(res_intellectuals_nonviolent, y = "Polyarchy", x = "Nonviolent Intellectuals")
))

socgroup_result$strategy <- gsub("(.*iolent) .*", "\\1", socgroup_result$treatment)
socgroup_result$socgroup <- gsub(".*iolent (.*)", "\\1", socgroup_result$treatment)
socgroup_result$socgroup <- factor(socgroup_result$socgroup, levels = c("Workers", "Students", "Military", "Peasants", "Urban mid. class", "Intellectuals"))
socgroup_result$time <- factor(socgroup_result$time, levels = c(0:10))

socgroup_result_plot <- ggplot(socgroup_result, aes(x = time, y = estimate, ymax = X97.5., ymin = X2.5.)) +
  facet_grid(socgroup ~ strategy) +
  geom_point(size = 4, position = position_dodge(width = 0.1)) +
  geom_errorbar(width = 0.1, linewidth = 2, position = position_dodge(width = 0.1)) +
  geom_hline(yintercept = 0) +
  theme_minimal() +
  xlab("Years since movement start") +
  ylab("Change in Polyarchy") +
  #labs(title = "ATT for campaigns of violent vs nonviolent strategy on Polyarchy over time") +
  theme(axis.text = element_text(size = 18),
        axis.title = element_text(size = 18),
        legend.text = element_text(size = 18),
        legend.title = element_text(size = 18),
        plot.title = element_text(size = 18),
        strip.background = element_rect(fill = "grey80", color = "white"),
        strip.text = element_text(size = 16))
ggsave(filename = "Output/Figure11.jpg", socgroup_result_plot, width = 12, heigh = 12)




```

## Social groups tabular

```{r tabular_socgroup, eval = TRUE}

#####     Make results-frame
socgroup_result <- bind_rows(list(panelmatch_resultframe(res_workers_violent, y = "Polyarchy", x = "Violent Workers"),
                                  panelmatch_resultframe(res_workers_nonviolent, y = "Polyarchy", x = "Nonviolent Workers"),
                                  
                                  panelmatch_resultframe(res_students_violent, y = "Polyarchy", x = "Violent Students"),
                                  panelmatch_resultframe(res_students_nonviolent, y = "Polyarchy", x = "Nonviolent Students"),
                                  
                                  panelmatch_resultframe(res_military_violent, y = "Polyarchy", x = "Violent Military"),
                                  panelmatch_resultframe(res_military_nonviolent, y = "Polyarchy", x = "Nonviolent Military"),
                                  
                                  panelmatch_resultframe(res_peasants_violent, y = "Polyarchy", x = "Violent Peasants"),
                                  panelmatch_resultframe(res_peasants_nonviolent, y = "Polyarchy", x = "Nonviolent Peasants"),
                                  
                                  panelmatch_resultframe(res_urbmid_violent, y = "Polyarchy", x = "Violent Urban mid. class"),
                                  panelmatch_resultframe(res_urbmid_nonviolent, y = "Polyarchy", x = "Nonviolent Urban mid. class"),
                                  
                                  panelmatch_resultframe(res_intellectuals_violent, y = "Polyarchy", x = "Violent Intellectuals"),
                                  panelmatch_resultframe(res_intellectuals_nonviolent, y = "Polyarchy", x = "Nonviolent Intellectuals")
))

socgroup_result$strategy <- gsub("(.*iolent) .*", "\\1", socgroup_result$treatment)
socgroup_result$socgroup <- gsub(".*iolent (.*)", "\\1", socgroup_result$treatment)
socgroup_result$socgroup <- factor(socgroup_result$socgroup, levels = c("Workers", "Students", "Military", "Peasants", "Urban mid. class", "Intellectuals"))
socgroup_result$Time <- paste0("T+", socgroup_result$time)
socgroup_result$Time <- factor(socgroup_result$Time, levels =  paste0("T+", 0:10))
socgroup_result[, c("X2.5.", "X97.5.")] <- NULL
socgroup_result$estimate  <- ifelse(abs(socgroup_result$estimate) / abs(socgroup_result$std.error) >= 1.97,  paste0( as.character(round(as.numeric(socgroup_result$estimate) , 4)), "*"),
                                    as.character(round(as.numeric(socgroup_result$estimate) , 4)) )
socgroup_result$std.error <- paste0( "(", round(as.numeric(socgroup_result$std.error), 4), ")")
socgroup_result <- socgroup_result[ , c("estimate", "std.error", "Time", "treatment", "strategy", "socgroup")]


viol_socgroup_results <- socgroup_result %>% subset(strategy == "Violent") %>% pivot_longer(estimate:std.error, values_to = "Violent") %>% select(-treatment, -strategy)
viol_socgroup_results <- viol_socgroup_results %>% pivot_wider(names_from = socgroup, values_from = "Violent") %>% select(-name)

viol_ndat <- tibble("Time" = c("N treated", "Sum of control units"),
                    "Workers"      = as.character(c(length(res_workers_violent$matched.sets)  , sum(sapply(res_workers_violent$matched.sets   , function(x) length(x))) )),
                    "Students"     = as.character(c(length(res_students_violent$matched.sets) , sum(sapply(res_students_violent$matched.sets, function(x) length(x))) )), 
                    "Military"    = as.character(c(length(res_military_violent$matched.sets) , sum(sapply(res_military_violent$matched.sets, function(x) length(x))) )), 
                    "Peasants" = as.character(c(length(res_peasants_violent$matched.sets) , sum(sapply(res_peasants_violent$matched.sets, function(x) length(x))) )), 
                    "Urban mid. class" = as.character(c(length(res_urbmid_violent$matched.sets)   , sum(sapply(res_urbmid_violent$matched.sets, function(x) length(x))) )), 
                    "Intellectuals" = as.character(c(length(res_intellectuals_violent$matched.sets)   , sum(sapply(res_intellectuals_violent$matched.sets, function(x) length(x))) )) )
viol_socgroup_results <- bind_rows(viol_socgroup_results, viol_ndat)
viol_socgroup_results$Time[seq(2, nrow(viol_socgroup_results)-2, 2)] <- ""


nvio_socgroup_results <- socgroup_result %>% subset(strategy == "Nonviolent") %>% pivot_longer(estimate:std.error, values_to = "Nonviolent") %>% select(-treatment, -strategy)
nvio_socgroup_results <- nvio_socgroup_results %>% pivot_wider(names_from = socgroup, values_from = "Nonviolent") %>% select(-name)

nvio_ndat <- tibble("Time" = c("N treated", "Sum of control units"),
                    "Workers"      = as.character(c(length(res_workers_nonviolent$matched.sets)  , sum(sapply(res_workers_nonviolent$matched.sets, function(x) length(x))) )),
                    "Students"     = as.character(c(length(res_students_nonviolent$matched.sets) , sum(sapply(res_students_nonviolent$matched.sets, function(x) length(x))) )), 
                    "Military"    = as.character(c(length(res_military_nonviolent$matched.sets) , sum(sapply(res_military_nonviolent$matched.sets, function(x) length(x))) )), 
                    "Peasants" = as.character(c(length(res_peasants_nonviolent$matched.sets) , sum(sapply(res_peasants_nonviolent$matched.sets, function(x) length(x))) )), 
                    "Urban mid. class" = as.character(c(length(res_urbmid_nonviolent$matched.sets)   , sum(sapply(res_urbmid_nonviolent$matched.sets, function(x) length(x))) )), 
                    "Intellectuals" = as.character(c(length(res_intellectuals_nonviolent$matched.sets)   , sum(sapply(res_intellectuals_nonviolent$matched.sets, function(x) length(x))) )) )

nvio_socgroup_results <- bind_rows(nvio_socgroup_results, nvio_ndat)
nvio_socgroup_results$Time[seq(2, nrow(nvio_socgroup_results)-2, 2)] <- ""

addtorow <- list()
addtorow$pos <- list(nrow(viol_socgroup_results))
addtorow$command <- paste0(paste0('\\hline \\multicolumn{5}{l}{', "\\textit{* p \\textless 0.05. Standard errors in parentheses}", '}', collapse=''), '\\\\')

#
print(xtable(viol_socgroup_results, caption = "ATT for violent protest movements on subsequent Polyarchy-
scores across different social groups", label = "tab:socgroup_results_violent"), add.to.row = addtorow, include.rownames = FALSE, caption.placement = "top", size = "scriptsize",
hline.after = c(-1, 0, nrow(viol_socgroup_results)-2),
table.placement = "!htbp", file = "Output/TableC8.tex")

print(xtable(nvio_socgroup_results, caption = "ATT for nonviolent protest movements on subsequent Polyarchy-
scores across different social groups", label = "tab:socgroup_results_nonviolent"), add.to.row = addtorow, include.rownames = FALSE, caption.placement = "top", size = "scriptsize",
hline.after = c(-1, 0, nrow(nvio_socgroup_results)-2),
table.placement = "!htbp", file = "Output/TableC9.tex")


```

#Era-separated

Split dataset into different periods and rerun PanelMatch

```{r era, eval = TRUE}

#####     20th century only     #####
modeldat_20th <- cy_omg[cy_omg$year>1899, c("country_id", "year", "onset_violent", "onset_nonviolent", "campaign_strategy_violent_lag1", "v2x_polyarchy", "campaign_strategy_nonviolent_lag1", "latent_gdppc_mean_log", "ln_pop")]


#PanelMatch
mod_violent_20th <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = modeldat_20th, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_violent", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
)

#Stage 3
res_violent_20th <- PanelEstimate(sets = mod_violent_20th, data = modeldat_20th)


#PanelMatch
mod_nonviolent_20th <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = modeldat_20th, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviolent", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
)

#Stage 3
res_nonviolent_20th <- PanelEstimate(sets = mod_nonviolent_20th, data = modeldat_20th)


#####     19th century only     #####
modeldat_19th <- cy_omg[cy_omg$year<=1899,  c("country_id", "year", "onset_violent", "onset_nonviolent", "campaign_strategy_violent_lag1", "v2x_polyarchy", "campaign_strategy_nonviolent_lag1", "latent_gdppc_mean_log", "ln_pop")]


#PanelMatch
mod_violent_19th <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = modeldat_19th, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_violent", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
)

#Stage 3
res_violent_19th <- PanelEstimate(sets = mod_violent_19th, data = modeldat_19th)


#PanelMatch
mod_nonviolent_19th <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = modeldat_19th, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviolent", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
)

#Stage 3
res_nonviolent_19th <- PanelEstimate(sets = mod_nonviolent_19th, data = modeldat_19th)

####    After WW2     #####
modeldat_WW2 <- cy_omg[cy_omg$year>1945,  c("country_id", "year", "onset_violent", "onset_nonviolent", "campaign_strategy_violent_lag1", "v2x_polyarchy", "campaign_strategy_nonviolent_lag1", "latent_gdppc_mean_log", "ln_pop")]

#PanelMatch
mod_violent_WW2 <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = modeldat_WW2, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_violent", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
)

#Stage 3
res_violent_WW2 <- PanelEstimate(sets = mod_violent_WW2, data = modeldat_WW2)


#PanelMatch
mod_nonviolent_WW2 <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = modeldat_WW2, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviolent", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
)

#Stage 3
res_nonviolent_WW2 <- PanelEstimate(sets = mod_nonviolent_WW2, data = modeldat_WW2)


```

## Time-results

```{r, era_results, eval = TRUE}

#####     Make results-frame
era_results <- bind_rows(list(panelmatch_resultframe(res_violent_19th, y = "Polyarchy", x = "Violent Before 1900"),
                              panelmatch_resultframe(res_nonviolent_19th, y = "Polyarchy", x = "Nonviolent Before 1900"),
                              
                              panelmatch_resultframe(res_violent_20th, y = "Polyarchy", x = "Violent After 1900"),
                              panelmatch_resultframe(res_nonviolent_20th, y = "Polyarchy", x = "Nonviolent After 1900"),
                              
                              panelmatch_resultframe(res_violent_WW2, y = "Polyarchy", x = "Violent After 1945"),
                              panelmatch_resultframe(res_nonviolent_WW2, y = "Polyarchy", x = "Nonviolent After 1945")
))

era_results$strategy <- gsub("(.*iolent) .*", "\\1", era_results$treatment)
era_results$era <- gsub(".*iolent (.*)", "\\1", era_results$treatment)
era_results$era <- factor(era_results$era, levels = c("Before 1900", "After 1900", "After 1945"))
era_results$time <- factor(era_results$time, levels = c(0:10))

era_result_plot <- ggplot(era_results, aes(x = time, y = estimate, ymax = X97.5., ymin = X2.5.)) +
  facet_grid(era ~ strategy) +
  geom_point(size = 4, position = position_dodge(width = 0.1)) +
  geom_errorbar(width = 0.1, linewidth = 2, position = position_dodge(width = 0.1)) +
  geom_hline(yintercept = 0) +
  theme_minimal() +
  xlab("Years since movement start") +
  ylab("Change in Polyarchy") +
  #labs(title = "ATT for campaigns of violent vs nonviolent strategy on Polyarchy over time") +
  theme(axis.text = element_text(size = 18),
        axis.title = element_text(size = 18),
        legend.text = element_text(size = 18),
        legend.title = element_text(size = 18),
        plot.title = element_text(size = 18),
        strip.background = element_rect(fill = "grey80", color = "white"),
        strip.text = element_text(size = 18))

ggsave(filename = "Output/Figure8.jpg", era_result_plot, width = 12, height = 12)


```

## Pretrend time

Extract pre-trend info for the time-results

```{r pretrend_time, eval = TRUE}
pre_violent_19th    <- get_pretrend_function(mod_violent_19th    , covs = c("v2x_polyarchy", "campaign_strategy_nonviolent_lag1",  "campaign_strategy_violent_lag1", "latent_gdppc_mean_log", "ln_pop" ), strat = "Violent strategy", gol = "Before 1900", dat = modeldat_19th)
pre_nonviolent_19th <- get_pretrend_function(mod_nonviolent_19th , covs = c("v2x_polyarchy", "campaign_strategy_nonviolent_lag1",  "campaign_strategy_violent_lag1", "latent_gdppc_mean_log", "ln_pop" ), strat = "Nonviolent strategy", gol = "Before 1900", dat = modeldat_19th)

pre_violent_20th    <- get_pretrend_function(mod_violent_20th   , covs = c("v2x_polyarchy", "campaign_strategy_nonviolent_lag1",  "campaign_strategy_violent_lag1", "latent_gdppc_mean_log", "ln_pop" ), strat = "Violent strategy"    , gol = "After 1900", dat = modeldat_20th)
pre_nonviolent_20th <- get_pretrend_function(mod_nonviolent_20th, covs = c("v2x_polyarchy", "campaign_strategy_nonviolent_lag1",  "campaign_strategy_violent_lag1",  "latent_gdppc_mean_log", "ln_pop" ), strat = "Nonviolent strategy", gol = "After 1900", dat = modeldat_20th)

pre_violent_WW2    <- get_pretrend_function(mod_violent_WW2   , covs = c("v2x_polyarchy", "campaign_strategy_nonviolent_lag1",  "campaign_strategy_violent_lag1", "latent_gdppc_mean_log", "ln_pop" ), strat = "Violent strategy"    , gol = "After 1945", dat = modeldat_WW2)
pre_nonviolent_WW2 <- get_pretrend_function(mod_nonviolent_WW2, covs = c("v2x_polyarchy",  "campaign_strategy_nonviolent_lag1",  "campaign_strategy_violent_lag1",  "latent_gdppc_mean_log", "ln_pop" ), strat = "Nonviolent strategy", gol = "After 1945", dat = modeldat_WW2)

pre_time <- bind_rows(list(pre_violent_19th, pre_nonviolent_19th, pre_violent_20th, pre_nonviolent_20th, pre_violent_WW2, pre_nonviolent_WW2) )
pre_time$strategy <- factor(pre_time$strategy, levels = c("Nonviolent strategy", "Violent strategy"))
pre_time$time     <- gsub("t_", "T-", pre_time$time)
pre_time$time     <- factor(pre_time$time, levels = paste0("T-", 10:1))
pre_time$time_num <- as.numeric(gsub("T", "", pre_time$time))
pre_time$era <- factor(pre_time$goal, levels = c("Before 1900", "After 1900", "After 1945"))


#pre_goal$time <- factor(pre_goal$time, levels = c(0:10))
pre_time <- pre_time %>% mutate("Covariate" = case_when(
  name ==  "v2x_polyarchy" ~ "Polyarchy",
  name ==  "campaign_strategy_violent_lag1" ~ "Violent movements",
  name ==  "campaign_strategy_nonviolent_lag1" ~ "Nonviolent movements",
  name ==  "latent_gdppc_mean_log" ~ "Ln GDP per capita",
  name ==  "ln_pop" ~ "Ln population"))

era_pretrend <- ggplot(pre_time, aes(x = time_num, y = value, color = Covariate)) +
  facet_grid(era ~ strategy) +
  geom_line() +
  geom_point() +
  xlab("Years before treatment") + ylab("Standardized Mean difference for experiencing onset") +
  #scale_y_continuous(limits = c(-0.1, 0.1)) +
  scale_x_continuous(n.breaks = 10) +
  geom_hline(yintercept = 0) +
  theme_minimal() +
  theme(text = element_text(size = 18),
        axis.title.y = element_text(size = 16),
        strip.text = element_text(size = 16),
        strip.background = element_rect(fill = "grey80", color = "white"))
ggsave(filename = "Output/FigureC2.jpg", era_pretrend, width = 12, height = 10)



```

## Time-results tabular-format

```{r tabular_era, eval = TRUE}

#Result
era_results <- bind_rows(list(panelmatch_resultframe(res_violent_19th, y = "Polyarchy", x = "Violent Before 1900"),
                              panelmatch_resultframe(res_nonviolent_19th, y = "Polyarchy", x = "Nonviolent Before 1900"),
                              
                              panelmatch_resultframe(res_violent_20th, y = "Polyarchy", x = "Violent After 1900"),
                              panelmatch_resultframe(res_nonviolent_20th, y = "Polyarchy", x = "Nonviolent After 1900"),
                              
                              panelmatch_resultframe(res_violent_WW2, y = "Polyarchy", x = "Violent After 1945"),
                              panelmatch_resultframe(res_nonviolent_WW2, y = "Polyarchy", x = "Nonviolent After 1945")
))
era_results$strategy <- gsub("(.*iolent) .*", "\\1", era_results$treatment)
era_results$era <- gsub(".*iolent (.*)", "\\1", era_results$treatment)
era_results$era <- factor(era_results$era, levels = c("Before 1900", "After 1900", "After 1945"))
era_results$Time <- paste0("T+", era_results$time)
era_results$Time <- factor(era_results$Time, levels =  paste0("T+", 0:10))
era_results[, c("X2.5.", "X97.5.")] <- NULL
era_results$estimate  <- ifelse(abs(era_results$estimate) / abs(era_results$std.error) >= 1.97,  paste0( as.character(round(as.numeric(era_results$estimate) , 4)), "*"),
                                as.character(round(as.numeric(era_results$estimate) , 4)) )

era_results$std.error <- paste0( "(", round(as.numeric(era_results$std.error), 4), ")")
era_results <- era_results[ , c("estimate", "std.error", "Time", "treatment", "strategy", "era")]


viol_era_results <- era_results %>% subset(strategy == "Violent") %>% pivot_longer(estimate:std.error, values_to = "Violent") %>% select(-treatment, -strategy)
viol_era_results <- viol_era_results %>% pivot_wider(names_from = era, values_from = "Violent") %>% select(-name)

viol_ndat <- tibble("Time" = c("N treated", "Sum of control units"),
                    "Before 1900"     = as.character(c(length(res_violent_19th$matched.sets)   , sum(sapply(res_violent_19th$matched.sets   , function(x) length(x))) )),
                    "After 1900" = as.character(c(length(res_violent_20th$matched.sets), sum(sapply(res_violent_20th$matched.sets, function(x) length(x))) )), 
                    "After 1945" = as.character(c(length(res_violent_WW2$matched.sets), sum(sapply(res_violent_WW2$matched.sets, function(x) length(x))) )))
viol_era_results <- bind_rows(viol_era_results, viol_ndat)
viol_era_results$Time[seq(2, nrow(viol_era_results)-2, 2)] <- ""


nvio_era_results <- era_results %>% subset(strategy == "Nonviolent") %>% pivot_longer(estimate:std.error, values_to = "Nonviolent") %>% select(-treatment, -strategy)
nvio_era_results <- nvio_era_results %>% pivot_wider(names_from = era, values_from = "Nonviolent") %>% select(-name)

nvio_ndat <- tibble("Time" = c("N treated", "Sum of control units"),
                    "Before 1900" = as.character(c(length(res_nonviolent_19th$matched.sets)  , sum(sapply(res_nonviolent_19th$matched.sets, function(x) length(x))) )),
                    "After 1900"  = as.character(c(length(res_nonviolent_20th$matched.sets)  , sum(sapply(res_nonviolent_20th$matched.sets, function(x) length(x))) )), 
                    "After 1945"  = as.character(c(length(res_nonviolent_WW2$matched.sets)   , sum(sapply(res_nonviolent_WW2$matched.sets, function(x) length(x))) )))
nvio_era_results <- bind_rows(nvio_era_results, nvio_ndat)
nvio_era_results$Time[seq(2, nrow(nvio_era_results)-2, 2)] <- ""

addtorow <- list()
addtorow$pos <- list(nrow(viol_era_results))
addtorow$command <- paste0(paste0('\\hline \\multicolumn{5}{l}{', "\\textit{* p \\textless 0.05. Standard errors in parentheses}", '}', collapse=''), '\\\\')


#
print(xtable(viol_era_results, caption = "ATT for violent protest movements on subsequent Polyarchy-
scores across different time periods", label = "tab:era_results_violent"), add.to.row = addtorow, include.rownames = FALSE, caption.placement = "top", size = "scriptsize",
hline.after = c(-1, 0, nrow(viol_era_results)-2),
table.placement = "!htbp", file = "Output/TableC2.tex")

print(xtable(nvio_era_results, caption = "ATT for nonviolent protest movements on subsequent Polyarchy-
scores across different time periods", label = "tab:era_results_nonviolent"), add.to.row = addtorow, include.rownames = FALSE, caption.placement = "top", size = "scriptsize",
hline.after = c(-1, 0, nrow(nvio_era_results)-2),
table.placement = "!htbp", file = "Output/TableC3.tex")


```

# Flank Benchmark

```{r panelmatch_fullsample, eval = TRUE}
flank_modeldat <- cy_omg[, c("country_id", "year", "onset_nonviolent_flank", "onset_violent_flank", "ongoing_violent_with_flank_lag1", "v2x_polyarchy", "ongoing_nonviolent_with_flank_lag1", "latent_gdppc_mean_log", "ln_pop")]

#PanelMatch
mod_violent_flank <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = flank_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_violent_flank", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("ongoing_violent_with_flank_lag1", "ongoing_nonviolent_with_flank_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_nonviolent, 1:10)) + I(lag(campaign_strategy_violent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)

#Stage 3
res_violent_flank <- PanelEstimate(sets = mod_violent_flank, data = flank_modeldat)

#PanelMatch
mod_nonviolent_flank <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = flank_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviolent_flank", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("ongoing_nonviolent_with_flank_lag1", "ongoing_nonviolent_with_flank_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #+ I(lag(campaign_strategy_nonviolent, 1:10)) + I(lag(campaign_strategy_violent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)

#Stage 3
res_nonviolent_flank <- PanelEstimate(sets = mod_nonviolent_flank, data = flank_modeldat)

```

## Plot flank-result

This plots the results for the PanelMatch of the full sample

```{r plot_fullsample, eval = TRUE}

#Result
flank_resframe <- data.frame(rbind(cbind(summary(res_violent_flank)$summary,
                                         "Strategy"="Violent", "time" = paste0("t+", 0:10)),
                                   cbind(summary(res_nonviolent_flank)$summary, "Strategy" = "Nonviolent", "time" = paste0("t+", 0:10))))
flank_resframe$estimate <- as.numeric(flank_resframe$estimate)
flank_resframe$X2.5. <- as.numeric(flank_resframe$X2.5.)
flank_resframe$X97.5. <- as.numeric(flank_resframe$X97.5.)
flank_resframe$time <- factor(flank_resframe$time, levels =  paste0("t+", 0:10))

flank_results <- ggplot(flank_resframe, aes(x = time, y = estimate, ymax = X97.5., ymin = X2.5., color = Strategy)) +
  geom_point(size = 4, position = position_dodge(width = 0.1)) +
  geom_errorbar(width = 0.1, linewidth = 2, position = position_dodge(width = 0.1)) +
  geom_hline(yintercept = 0) +
  theme_minimal() +
  xlab("Years since movement start") +
  ylab("Change in Polyarchy") +
  scale_color_manual(values = c("black", "grey")) +
  #labs(title = "ATT for campaigns of violent vs nonviolent strategy on Polyarchy over time") +
  theme(axis.text = element_text(size = 18),
        axis.title = element_text(size = 18),
        legend.text = element_text(size = 18),
        legend.title = element_text(size = 18),
        plot.title = element_text(size = 18))
ggsave(filename = "Output/FigureC3.jpg", flank_results, width = 12, heigh = 8)

```

## Tabular flank results

```{r tabular_fullsample, eval = TRUE}

#Result
flank_resframe <- data.frame(rbind(cbind(summary(res_violent_flank)$summary,
                                         "Strategy"="Violent", "Time" = paste0("T+", 0:10)),
                                   cbind(summary(res_nonviolent_flank)$summary, "Strategy" = "Nonviolent", "Time" = paste0("T+", 0:10))))
#flank_resframe$estimate  <- as.character(round(as.numeric(flank_resframe$estimate) , 4))
flank_resframe$estimate <- as.numeric(flank_resframe$estimate)
flank_resframe$std.error <- as.numeric(flank_resframe$std.error)

flank_resframe$estimate  <- ifelse(abs(flank_resframe$estimate) / abs(flank_resframe$std.error) >= 1.97,  paste0( as.character(round(as.numeric(flank_resframe$estimate) , 4)), "*"),
                                   as.character(round(as.numeric(flank_resframe$estimate) , 4)) )

flank_resframe$std.error <- paste0( "(", round(as.numeric(flank_resframe$std.error), 4), ")")
flank_resframe$X2.5.     <- as.numeric(flank_resframe$X2.5.)
flank_resframe$X97.5.    <- as.numeric(flank_resframe$X97.5.)
flank_resframe$Time <- factor(flank_resframe$Time, levels =  paste0("T+", 0:10))
flank_resframe <- flank_resframe[ , c("estimate", "std.error", "Time", "Strategy")]

viol_flank_resframe <- flank_resframe %>% subset(Strategy == "Violent") %>% pivot_longer(estimate:std.error, values_to = "Violent") %>% select(-Strategy)
nvio_flank_resframe <- flank_resframe %>% subset(Strategy == "Nonviolent") %>% pivot_longer(estimate:std.error, values_to = "Nonviolent") %>% select(-Strategy)

flank_resframe <- full_join(viol_flank_resframe, nvio_flank_resframe)
flank_resframe$name <- NULL

ndat <- tibble("Time" = c("N treated", "Sum of control units"),
               "Violent"     = as.character(c(length(res_violent_flank$matched.sets)   , sum(sapply(res_violent_flank$matched.sets   , function(x) length(x))) )),
               "Nonviolent" = as.character(c(length(res_nonviolent_flank$matched.sets), sum(sapply(res_nonviolent_flank$matched.sets, function(x) length(x))) )))
flank_resframe <- bind_rows(flank_resframe, ndat)
flank_resframe$Time[seq(2, nrow(flank_resframe)-2, 2)] <- ""

addtorow <- list()
addtorow$pos <- list(nrow(flank_resframe))
addtorow$command <- paste0(paste0('\\hline \\multicolumn{3}{l}{', "\\textit{* p \\textless 0.05. Standard errors in parentheses}", '}', collapse=''), '\\\\')

#
print(xtable(flank_resframe, caption = "ATT for violent vs. nonviolent protest movements on subsequent Polyarchy-
scores", label = "tab:Fullsample_results"), add.to.row = addtorow, include.rownames = FALSE, caption.placement = "top", size = "footnotesize",
hline.after = c(-1, 0, nrow(flank_resframe)-2),
table.placement = "!htbp", file = "Output/TableC10.tex")



```

#Robustness: Other instability

```{r panelmatch_fullsample, eval = TRUE}
fullsample_modeldat <- cy_omg[, c("country_id", "year", "onset_nonviolent", "onset_violent", "campaign_strategy_violent_lag1", "v2x_polyarchy", "campaign_strategy_nonviolent_lag1",
                                  "v2svdomaut", "latent_gdppc_mean_log", "v2svindep", "e_civil_war", "ln_pop", "successful_coups")]

#PanelMatch
mod_violent_instability <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = fullsample_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_violent", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1", "v2svindep", "e_civil_war"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_nonviolent, 1:10)) + I(lag(campaign_strategy_violent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) + I(lag(v2svdomaut, 1:10)) + I(lag(successful_coups, 1:10)) ) #Formula for refinement
  
)

#Stage 3
res_violent_instability <- PanelEstimate(sets = mod_violent_instability, data = fullsample_modeldat)

#PanelMatch
mod_nonviolent_instability <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = fullsample_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviolent", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1", "v2svindep", "e_civil_war"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #+ I(lag(campaign_strategy_nonviolent, 1:10)) + I(lag(campaign_strategy_violent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) + I(lag(v2svdomaut, 1:10)) + I(lag(successful_coups, 1:10)) ) #Formula for refinement
  
)

#Stage 3
res_nonviolent_instability <- PanelEstimate(sets = mod_nonviolent_instability, data = fullsample_modeldat)




```

## Plot robustness-result

This plots the results for the PanelMatch of the full sample

```{r plot_fullsample, eval = TRUE}

#Result
fullsample_resframe_instability <- data.frame(rbind(cbind(summary(res_violent_instability)$summary,
                                                          "Strategy"="Violent", "time" = paste0("t+", 0:10)),
                                                    cbind(summary(res_nonviolent_instability)$summary, "Strategy" = "Nonviolent", "time" = paste0("t+", 0:10))))
fullsample_resframe_instability$estimate <- as.numeric(fullsample_resframe_instability$estimate)
fullsample_resframe_instability$X2.5. <- as.numeric(fullsample_resframe_instability$X2.5.)
fullsample_resframe_instability$X97.5. <- as.numeric(fullsample_resframe_instability$X97.5.)
fullsample_resframe_instability$time <- factor(fullsample_resframe_instability$time, levels =  paste0("t+", 0:10))

fullsample_results_instability <- ggplot(fullsample_resframe_instability, aes(x = time, y = estimate, ymax = X97.5., ymin = X2.5., color = Strategy)) +
  geom_point(size = 4, position = position_dodge(width = 0.1)) +
  geom_errorbar(width = 0.1, linewidth = 2, position = position_dodge(width = 0.1)) +
  geom_hline(yintercept = 0) +
  theme_minimal() +
  xlab("Years since movement start") +
  ylab("Change in Polyarchy") +
  scale_color_manual(values = c("black", "grey"))
ggsave(filename = "Output/FigureC4.jpg", fullsample_results_instability, width = 12, height = 8, scale =0.7)

```

# Ideology

We create separate treatments based on the ideology.

```{r panelmatch_ideology, eval = TRUE}
ide_modeldat <- cy_omg[, c("country_id", "year", "campaign_strategy_violent_lag1", "v2x_polyarchy", "campaign_strategy_nonviolent_lag1", "latent_gdppc_mean_log", "ln_pop",
                           grep("^onset_", colnames(cy_omg), value =T))]

#####     Socialist
#PanelMatch
mod_socialist_violent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = ide_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_viol_ide_socialist_marxist", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
)


#Stage 3
res_socialist_violent <- PanelEstimate(sets = mod_socialist_violent, data = ide_modeldat)


#PanelMatch
mod_socialist_nonviolent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = ide_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviol_ide_socialist_marxist", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)



#Stage 3
res_socialist_nonviolent <- PanelEstimate(sets = mod_socialist_nonviolent, data = ide_modeldat)

#####    Students
#PanelMatch
mod_demo_violent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = ide_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_viol_ide_democracy_hr", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)

#Stage 3
res_demo_violent <- PanelEstimate(sets = mod_demo_violent, data = ide_modeldat)


#PanelMatch
mod_demo_nonviolent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = ide_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviol_ide_democracy_hr", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)

#Stage 3
res_demo_nonviolent <- PanelEstimate(sets = mod_demo_nonviolent, data = ide_modeldat)


#####     Nationalist
#PanelMatch
mod_nationalist_violent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = ide_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_viol_ide_nationalist", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)

#Stage 3
res_nationalist_violent <- PanelEstimate(sets = mod_nationalist_violent, data = ide_modeldat)


#PanelMatch
mod_nationalist_nonviolent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = ide_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviol_ide_nationalist", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
  
)

#Stage 3
res_nationalist_nonviolent <- PanelEstimate(sets = mod_nationalist_nonviolent, data = ide_modeldat)

#####     Peasants
#PanelMatch
mod_conservative_violent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = ide_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_viol_ide_conservative", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
)

#Stage 3
res_conservative_violent <- PanelEstimate(sets = mod_conservative_violent, data = ide_modeldat)


#PanelMatch
mod_conservative_nonviolent <- PanelMatch(
  
  #General information for the PanelMatch-function:
  data = ide_modeldat, #Data to be used
  time.id = "year", #Name of time-column 
  unit.id = "country_id", #Name of unit-column
  treatment = "onset_nonviol_ide_conservative", #Name of treatment variable
  outcome.var = "v2x_polyarchy", #Name of outcome variable 
  qoi = "att", #Quantity of interest.
  verbose = TRUE, #Prints more information about all calculations
  
  #    Arguments for Stage 1:
  matching = TRUE, #Should Stage 1 exact match on treatment history?
  lag = 10, # This argument controls the number of lags, notated as "L" int he article
  match.missing = FALSE, # Should patterns of missingness be included in matching the units into sets?
  listwise.delete = TRUE, #Delete missingness listwise
  exact.match.variables = c("campaign_strategy_nonviolent_lag1", "campaign_strategy_violent_lag1"), #In principle, the exact matching in stage 1 can include all categorical variables, not just the treatment history. Character vector of relevant categorical variables can be added here. NULL means that we will only match on treatment history.
  
  #    Arguments referring to Stage 2:
  lead = 0:10, #How far (years) into the future should the outcome be measured? Notated as F in the article
  forbid.treatment.reversal = FALSE, #Should reversal be allowed in the period between the treatment occurs (T) and the outcome is measured (T + leads/F)
  refinement.method = "CBPS.weight", #Covariate balancing propensity score weights from Imai and Ratkovic (2014)
  size.match = 5, #Indicates the J closest matches to keep in the refinement. This is only relevant for the distance-methods, not weight-methods.
  covs.formula = as.formula(~ I(lag(v2x_polyarchy, 1:10)) + #I(lag(campaign_strategy_violent, 1:10)) + I(lag(campaign_strategy_nonviolent, 1:10)) +
                              I(lag(latent_gdppc_mean_log, 1:10)) + I(lag(ln_pop, 1:10)) ) #Formula for refinement
)

#Stage 3
res_conservative_nonviolent <- PanelEstimate(sets = mod_conservative_nonviolent, data = ide_modeldat)


```

## Social group results

```{r ide_results, eval = TRUE}

#####     Make results-frame
ide_result <- bind_rows(list(panelmatch_resultframe(res_socialist_violent, y = "Polyarchy", x = "Violent Socialism and Marxism"),
                             panelmatch_resultframe(res_socialist_nonviolent, y = "Polyarchy", x = "Nonviolent Socialism and Marxism"),
                             
                             panelmatch_resultframe(res_demo_violent, y = "Polyarchy", x = "Violent Democracy and HR"),
                             panelmatch_resultframe(res_demo_nonviolent, y = "Polyarchy", x = "Nonviolent Democracy and HR"),
                             
                             panelmatch_resultframe(res_nationalist_violent, y = "Polyarchy", x = "Violent Nationalism"),
                             panelmatch_resultframe(res_nationalist_nonviolent, y = "Polyarchy", x = "Nonviolent Nationalism"),
                             
                             panelmatch_resultframe(res_conservative_violent, y = "Polyarchy", x = "Violent Conservativism"),
                             panelmatch_resultframe(res_conservative_nonviolent, y = "Polyarchy", x = "Nonviolent Conservativism") ) )


ide_result$strategy <- gsub("(.*iolent) .*", "\\1", ide_result$treatment)
ide_result$ide <- gsub(".*iolent (.*)", "\\1", ide_result$treatment)
ide_result$ide <- factor(ide_result$ide, levels = c("Socialism and Marxism", "Democracy and HR", "Nationalism", "Conservativism"))
ide_result$time <- factor(ide_result$time, levels = c(0:10))

ide_result_plot <- ggplot(ide_result, aes(x = time, y = estimate, ymax = X97.5., ymin = X2.5.)) +
  facet_grid(ide ~ strategy) +
  geom_point(size = 4, position = position_dodge(width = 0.1)) +
  geom_errorbar(width = 0.1, linewidth = 2, position = position_dodge(width = 0.1)) +
  geom_hline(yintercept = 0) +
  theme_minimal() +
  xlab("Years since movement start") +
  ylab("Change in Polyarchy") +
  #labs(title = "ATT for campaigns of violent vs nonviolent strategy on Polyarchy over time") +
  theme(axis.text = element_text(size = 18),
        axis.title = element_text(size = 18),
        legend.text = element_text(size = 18),
        legend.title = element_text(size = 18),
        plot.title = element_text(size = 18),
        strip.background = element_rect(fill = "grey80", color = "white"),
        strip.text = element_text(size = 16))
ggsave(filename = "Output/Figure10.jpg", ide_result_plot, width = 12, heigh = 12)



```

## Ideology groups tabular

```{r tabular_ide, eval = TRUE}

#####     Make results-frame
ide_result <- bind_rows(list(panelmatch_resultframe(res_socialist_violent, y = "Polyarchy", x = "Violent Socialism and Marxism"),
                             panelmatch_resultframe(res_socialist_nonviolent, y = "Polyarchy", x = "Nonviolent Socialism and Marxism"),
                             
                             panelmatch_resultframe(res_demo_violent, y = "Polyarchy", x = "Violent Democracy and HR"),
                             panelmatch_resultframe(res_demo_nonviolent, y = "Polyarchy", x = "Nonviolent Democracy and HR"),
                             
                             panelmatch_resultframe(res_nationalist_violent, y = "Polyarchy", x = "Violent Nationalism"),
                             panelmatch_resultframe(res_nationalist_nonviolent, y = "Polyarchy", x = "Nonviolent Nationalism"),
                             
                             panelmatch_resultframe(res_conservative_violent, y = "Polyarchy", x = "Violent Conservativism"),
                             panelmatch_resultframe(res_conservative_nonviolent, y = "Polyarchy", x = "Nonviolent Conservativism") ) )


ide_result$strategy <- gsub("(.*iolent) .*", "\\1", ide_result$treatment)
ide_result$ide <- gsub(".*iolent (.*)", "\\1", ide_result$treatment)
ide_result$ide <- factor(ide_result$ide, levels = c("Socialism and Marxism", "Democracy and HR", "Nationalism", "Conservativism"))
ide_result$time <- factor(ide_result$time, levels = c(0:10))

ide_result$Time <- paste0("T+", ide_result$time)
ide_result$Time <- factor(ide_result$Time, levels =  paste0("T+", 0:10))
ide_result[, c("X2.5.", "X97.5.")] <- NULL
ide_result$estimate  <- ifelse(abs(ide_result$estimate) / abs(ide_result$std.error) >= 1.97,  paste0( as.character(round(as.numeric(ide_result$estimate) , 4)), "*"),
                                    as.character(round(as.numeric(ide_result$estimate) , 4)) )
ide_result$std.error <- paste0( "(", round(as.numeric(ide_result$std.error), 4), ")")
ide_result <- ide_result[ , c("estimate", "std.error", "Time", "treatment", "strategy", "ide")]


viol_ide_results <- ide_result %>% subset(strategy == "Violent") %>% pivot_longer(estimate:std.error, values_to = "Violent") %>% select(-treatment, -strategy)
viol_ide_results <- viol_ide_results %>% pivot_wider(names_from = ide, values_from = "Violent") %>% select(-name)

viol_ndat <- tibble("Time" = c("N treated", "Sum of control units"),
                    "Socialism and Marxism"      = as.character(c(length(res_socialist_violent$matched.sets)  , sum(sapply(res_socialist_violent$matched.sets   , function(x) length(x))) )),
                    "Democracy and HR"     = as.character(c(length(res_demo_violent$matched.sets) , sum(sapply(res_demo_violent$matched.sets, function(x) length(x))) )), 
                    "Nationalism"    = as.character(c(length(res_nationalist_violent$matched.sets) , sum(sapply(res_nationalist_violent$matched.sets, function(x) length(x))) )), 
                    "Conservativism" = as.character(c(length(res_conservative_violent$matched.sets) , sum(sapply(res_conservative_violent$matched.sets, function(x) length(x))) ))
                    )

viol_ide_results <- bind_rows(viol_ide_results, viol_ndat)
viol_ide_results$Time[seq(2, nrow(viol_ide_results)-2, 2)] <- ""


nvio_ide_results <- ide_result %>% subset(strategy == "Nonviolent") %>% pivot_longer(estimate:std.error, values_to = "Nonviolent") %>% select(-treatment, -strategy)
nvio_ide_results <- nvio_ide_results %>% pivot_wider(names_from = ide, values_from = "Nonviolent") %>% select(-name)

nvio_ndat <- tibble("Time" = c("N treated", "Sum of control units"),
                    "Socialism and Marxism"      = as.character(c(length(res_socialist_nonviolent$matched.sets)  , sum(sapply(res_socialist_nonviolent$matched.sets, function(x) length(x))) )),
                    "Democracy and HR"     = as.character(c(length(res_demo_nonviolent$matched.sets) , sum(sapply(res_demo_nonviolent$matched.sets, function(x) length(x))) )), 
                    "Nationalism"    = as.character(c(length(res_nationalist_nonviolent$matched.sets) , sum(sapply(res_nationalist_nonviolent$matched.sets, function(x) length(x))) )), 
                    "Conservativism" = as.character(c(length(res_conservative_violent$matched.sets) , sum(sapply(res_conservative_nonviolent$matched.sets, function(x) length(x))) ))  )

nvio_ide_results <- bind_rows(nvio_ide_results, nvio_ndat)
nvio_ide_results$Time[seq(2, nrow(nvio_ide_results)-2, 2)] <- ""

addtorow <- list()
addtorow$pos <- list(nrow(viol_ide_results))
addtorow$command <- paste0(paste0('\\hline \\multicolumn{5}{l}{', "\\textit{* p \\textless 0.05. Standard errors in parentheses}", '}', collapse=''), '\\\\')


#
print(xtable(viol_ide_results, caption = "ATT for violent protest movements on subsequent Polyarchy-scores across different social groups", label = "tab:ide_results_violent"), add.to.row = addtorow, include.rownames = FALSE, caption.placement = "top", size = "scriptsize",
hline.after = c(-1, 0, nrow(viol_ide_results)-2),
table.placement = "!htbp", file = "Output/TableC4.tex")

print(xtable(nvio_ide_results, caption = "ATT for nonviolent protest movements on subsequent Polyarchy-
scores across different social groups", label = "tab:ide_results_nonviolent"), add.to.row = addtorow, include.rownames = FALSE, caption.placement = "top", size = "scriptsize",
hline.after = c(-1, 0, nrow(nvio_ide_results)-2),
table.placement = "!htbp", file = "Output/TableC5.tex")



```
